import { Flex, Pagination, Table, theme } from 'antd'
import './index.scss'
import { TableProps } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { throttle } from 'lodash'

interface MyTableProps extends TableProps {
  pageSize?: number
  tableHeight?: string
  total?: number
  loading?: boolean
  height?: string
  page?: boolean
  onPaginationChange?: (page: number, pageSize: number) => void
}
function MyTable(props: MyTableProps) {
  const {
    dataSource,
    columns,
    size = 'small',
    pageSize = 20,
    total = 0,
    page = true,
    onPaginationChange,
    loading = true,
    height = '',
  } = props

  const {
    token: { colorPrimary },
  } = theme.useToken()

  const [tableHeight, setTableHeight] = useState<number>(100)

  const tableRef = useRef(null)

  useEffect(() => {
    const getTableHeight = throttle(() => {
      if (tableRef.current) {
        const tableDom: any = tableRef.current
        if (tableDom) {
          const height = tableDom.offsetHeight
          setTableHeight(height - 70)
        }
      }
    }, 300)
    getTableHeight()
    window.addEventListener('resize', getTableHeight)
    return () => {
      window.removeEventListener('resize', getTableHeight)
    }
  }, [])
  return (
    <Flex
      className="my-table"
      style={{ height: height ? height : '100%' }}
      vertical>
      <div className="table-count" style={{ color: colorPrimary }}>
        共 {dataSource?.length} 条
      </div>
      <div className="table-content">
        <Table
          ref={tableRef}
          className="table"
          bordered
          dataSource={dataSource}
          pagination={false}
          columns={columns}
          size={size}
          scroll={{
            y: tableHeight,
            scrollToFirstRowOnChange: true,
          }}
          {...props}
        />
        {page ? (
          <Pagination
            disabled={loading}
            className="my-pagination"
            size="small"
            total={total}
            pageSizeOptions={['20', '50', '100']}
            pageSize={pageSize}
            onChange={onPaginationChange}></Pagination>
        ) : null}
      </div>
    </Flex>
  )
}

export default MyTable
